<template>
	<view class="session-list">
		<!-- topbar -->
		<topbar />
		<!-- 搜索栏 -->
		<searchBar @searchWordKey="searchWordKey" :isSearch="isSearch" @changeSeachState="changeSeachState" />
		<!-- 会话列表 -->
		<scroll-view scroll-y class="session-list-scroll-view" refresher-enabled :refresher-triggered="triggered"
			:refresher-threshold="100" refresher-background="#ecf5ff" @refresherrefresh="onRefresh"
			@scrolltolower="scrolltolower" @scrolltoupper="scrolltoupper" @scroll="$u.throttle(scroll,500)"
			:scroll-into-view="`sessionItem${scrollCurrentId}`">
			<!-- 会话项 -->
			<sessionItem v-for="(item,index) in recentlySessionList" :sessionItemInfo="item" :key="item.channelId"
				@setUnreadNum="$set(item, 'unreadNum', 0)" ref="sessionItem" @click.native="toDetail(item)"
				:id="`sessionItem${item.sessionId}`" />
			<!-- 空列表占位图 -->
			<view class="empty" v-if="!recentlySessionList.length" />
			<u-loadmore :status="status" v-if="isShowStatus" style="height:100rpx !important;"
				@click.native="scrolltolower" />
		</scroll-view>
		<!-- tabbar -->
		<uni-transition mode-class="fade" :show="isSearch" class="group-session-list-wrapper">
			<groupList :groupSessionList="groupSessionList" :keyword="wordKey" @toDetail="toGroupDetail" />
		</uni-transition>
		<tabbar />
	</view>
</template>

<script>
	// tabbar
	import tabbar from "@/components/tabbar/tabbar.vue"
	// topbar
	import topbar from "./components/topbar/topbar.vue";
	// 搜索栏
	import searchBar from "./components/search-bar/searchBar.vue";
	// 会话项
	import sessionItem from "./components/session-item/sessionItem.vue";
	import groupList from "./components/group-list/groupList.vue";
	export default {
		components: {
			topbar,
			searchBar,
			sessionItem,
			tabbar,
			groupList
		},
		data() {
			return {
				//列表加载loading状态
				status: 'loadmore',
				//scrollview下拉状态
				triggered: false,
				//会话列表
				// sessionList: [],
				//搜索的关键字
				wordKey: '',
				//页码数
				pageNum: 1,
				//每页数据条数
				pageSize: 10,
				//点击tabbar按钮滚动到未读会话currentId
				scrollCurrentId: 0,
				notHandledSessionList: [],
				recentlySessionList: [],
				groupSessionList: [],
				quicklyConsultSessionList: [],
				specialConsultSessionList: [],
				isSearch: false,
				isShowStatus: false,
			}
		},

		watch: {
			//会话列表发生变化更新未读条数
			recentlySessionList: {
				handler(val) {
					console.log('会话列表发生变化更新未读条数>>>>>>>>>>>>>>>>>>>', val)
					this.setUnreadNum();
				},
				deep: true,
			}
		},
		async onLoad() {
			//监听新消息
			uni.$off('sessionListOnMessage');
			uni.$on('sessionListOnMessage', msg => {
				if(!this.isGetSessionCompleted){
					return
				}
				this.onMsgHandler(msg);
			})
			// //监听点击tabbar
			uni.$off('doubleTap');
			uni.$on('doubleTap', this.onDoubleTap);
			await this.$websocketStatus;
			this._freshing = false;
			setTimeout(() => {
				this.triggered = true;
			}, 100)
		},
		async onShow() {
			//设置未读消息条数
			this.setUnreadNum();
		},
		computed: {
			//过滤未读的会话列表
			unreadSessionList() {
				let unreadList = this.recentlySessionList.filter(item => item.unreadNum > 0);
				unreadList = unreadList.map(item => item.sessionId);
				return unreadList
			},
		},
		methods: {
			changeSeachState(e) {
				this.isSearch = e;
			},
			//跳转到详情页
			toDetail(item) {
				const session = {
					sessionId: item.sessionId,
					chatType: item.chatType,
					sessionName: item.sessionName.replace(/%/g, ' '),
				}
				this.$set(item, 'unreadNum', 0);
				this.$set(item, 'atList', []);
				this.$u.route(`/pages_chat/chat_detail/chatDetail?sessionInfo=${encodeURIComponent(JSON
						.stringify(session))}`);
			},
			toGroupDetail(item) {
				const {
					session,
					sessionIndex
				} = this.findSessionBySessionId(this.recentlySessionList, item.sessionId);
				if (session) {
					this.recentlySessionList.splice(sessionIndex, 1);
					this.recentlySessionList.unshift(session);
				} else {
					this.recentlySessionList.unshift(item);
				}
				this.isSearch = false;
				this.toDetail(item);
			},
			//下拉刷新的刷新回调
			async onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				this.triggered = true;
				console.log('请求数据。。。')
				await this.getSessionList();
				this.isShowStatus = true;
				this.scrolltolower();
			},
			//获取会话列表
			async getSessionList() {
				console.clear();
				//重置会话列表
				this.notHandledSessionList = [];
				this.groupSessionList = [];
				this.recentlySessionList = [];
				this.quicklyConsultSessionList = [];
				this.specialConsultSessionList = [];
				this.pageNum = 1;
				this.isShowStatus = false;
				this.status = 'loadmore';
				//调用环信会话列表接口
				try {
					const {
						data
					} = await uni.IM.getSessionList();
					this.notHandledSessionList.push(...data.channel_infos);
					console.log('未处理的环信会话列表>>>>>>>>>>>>>>>>>>', this.notHandledSessionList);
					const groupList = await this.$u.post(this.$restUrl.getGroupList, {
						phone: uni.IM.userId
					});
					this.groupSessionList.push(...this.groupListInit(groupList.data));
					console.log('已过滤群组会话列表>>>>>>>>>>>>>>>>', this.groupSessionList);
					//重置下拉刷新参数
					this.triggered = false;
					this._freshing = false;
					if (!this.notHandledSessionList.length) {
						this.$showToast('暂无会话')
						this.$u.vuex('isGetSessionCompleted',true);
						return Promise.reject()
					}

					return Promise.resolve();
				} catch (e) {
					console.log(e)
					this.triggered = false;
					this._freshing = false;
					this.$showToast('获取会话列表失败')
					this.$u.vuex('isGetSessionCompleted',true);
					return Promise.reject()
				}
			},
			//下拉到底部回调
			async scrolltolower() {
				if (this.status == 'loading' || this.status == 'nomore') {
					return
				}
				this.status = 'loading';
				this.scrollCurrentId = '';
				const currentNotHandledSessionList = [];
				const anchor = (this.pageNum - 1) * this.pageSize;
				for (let i = 0; i < this.pageNum * this.pageSize; i++) {
					if (!this.notHandledSessionList[anchor + i]) {
						break
					}
					currentNotHandledSessionList.push(this.notHandledSessionList[anchor + i]);
				}
				console.log('currentNotHandledSessionList>>>>>>>>>>>>>>>>', currentNotHandledSessionList)
				this.recentlySessionList.push(...await this.recentlySessionListInit(currentNotHandledSessionList));
				console.log('已格式化的环信会话列表>>>>>>>>>>>', this.recentlySessionList);
				if (this.recentlySessionList.length < this.notHandledSessionList.length) {
					this.status = 'loadmore';
				} else {
					this.status = 'nomore';
				}
				this.pageNum++;
				this.$u.vuex('isGetSessionCompleted',true);
			},
			//上划到顶部回调
			scrolltoupper() {
				if (this.scrollCurrentId == this.unreadSessionList[0]) {
					return
				}
				this.scrollCurrentId = '';
			},
			//环信会话格式化函数
			async recentlySessionListInit(sessionList) {
				let sessionListTemp = [];
				for (let item of sessionList) {
					if (uni.IM.getId(item.channel_id) == 'system') {
						continue
					}
					const {
						session
					} = this.findSessionBySessionId(this.recentlySessionList, uni.IM.getId(item.channel_id));
					if (session) {
						continue
					}
					let sessionItemTemp = {};
					sessionItemTemp.sessionId = uni.IM.getId(item.channel_id);
					sessionItemTemp.channelId = item.channel_id;
					sessionItemTemp.lastMsg = JSON.parse(item.meta.payload).bodies[0].msg;
					sessionItemTemp.messageType = JSON.parse(item.meta.payload).ext.messageType;
					sessionItemTemp.userName = JSON.parse(item.meta.payload).ext.userName;
					sessionItemTemp.unreadNum = item.unread_num;
					sessionItemTemp.chatType = uni.IM.getChatType(item.channel_id);
					sessionItemTemp.time = item.meta.timestamp;
					sessionItemTemp.senderId = JSON.parse(item.meta.payload).from;
					sessionItemTemp.atList = [];

					const groupSession = await this.findSessionBySessionId(this.groupSessionList, sessionItemTemp
						.sessionId);
					if (groupSession.session && sessionItemTemp.chatType == 'groupChat') {
						sessionItemTemp.sessionName = groupSession.session.sessionName;
						sessionItemTemp.sessionAvatar = groupSession.session.sessionAvatar;
						sessionItemTemp.atList = groupSession.session.atList;
					} else {
						const {
							sessionName,
							sessionAvatar
						} = await this.getSessionExtensionInfo(sessionItemTemp.sessionId.split('^')[0], sessionItemTemp
							.chatType);
						sessionItemTemp.sessionName = sessionName;
						sessionItemTemp.sessionAvatar = sessionAvatar;

					}
					sessionListTemp.push(sessionItemTemp);
				}
				return sessionListTemp
			},
			//群会话格式化函数
			groupListInit(groupList) {
				let sessionListTemp = [];
				groupList.forEach(item => {
					let sessionItemTemp = {};
					sessionItemTemp.channelId = uni.IM.createChannelIdBySessionId(item.groupid, 'groupChat');
					sessionItemTemp.sessionId = item.groupid;
					sessionItemTemp.lastMsg = undefined;
					sessionItemTemp.messageType = undefined;
					sessionItemTemp.sessionAvatar = undefined;
					sessionItemTemp.unreadNum = 0;
					sessionItemTemp.chatType = 'groupChat';
					sessionItemTemp.time = undefined;
					sessionItemTemp.senderId = undefined;
					sessionItemTemp.atList = item.is_at;
					sessionItemTemp.sessionName = item.groupname;
					sessionListTemp.push(sessionItemTemp);

				})
				return sessionListTemp
			},
			//获取会话扩展信息
			async getSessionExtensionInfo(sessionId, chatType) {
				if (chatType == 'groupChat') {
					const {
						data
					} = await uni.IM.getGroupInfo(sessionId);
					return {
						sessionName: data[0].name,
						sessionAvatar: '',
					};
				} else {
					//获取用户信息
					const {
						data
					} = await uni.IM.getSingleUserInfo(sessionId);
					return {
						sessionName: data[sessionId].nickname ? data[sessionId].nickname : '未设置用户名',
						sessionAvatar: data[sessionId].avatarurl,
					}
				}
			},
			//根据会话ID查找会话
			findSessionBySessionId(sessionList, sessionId) {
				let sessionIndex;
				const session = sessionList.find((item, index) => {
					sessionIndex = index;
					return item.sessionId == sessionId;
				});
				return {
					session,
					sessionIndex,
				};
			},
			//监听到新消息处理函数
			async onMsgHandler(msg) {
				let sessionId;
				if (msg.type == 'groupChat') {
					sessionId = msg.to;
				} else if (msg.type == 'singleChat') {
					sessionId = uni.IM.isSender({
						msgFromId: msg.from
					}) ? msg.to : msg.from;
				}
				const {
					session,
					sessionIndex
				} = this.findSessionBySessionId(this.recentlySessionList, sessionId);
				if (!session) {
					const newSession = await this.createSessionByMsg(msg, sessionId);
					return this.recentlySessionList.unshift(newSession);
				} else if (sessionId != this.currentSessionId) {
					this.$set(session, 'unreadNum', session.unreadNum + 1);
					if (msg.ext.mentionList && msg.ext.mentionList.length > 0) {
						this.$set(session, 'atList', [...new Set(session.atList.concat(msg.ext.mentionList))]);
					}
				}
				this.$set(session, 'time', msg.time);
				this.$set(session, 'lastMsg', msg.data);
				this.$set(session, 'messageType', msg.ext.messageType);
				this.$set(session, 'error', msg.error);
				this.$set(session, 'userName', msg.ext.userName);
				this.$set(session, 'senderId', msg.from);
				this.recentlySessionList.splice(sessionIndex, 1);
				this.recentlySessionList.unshift(session);
				this.$forceUpdate();
			},
			//根据新消息创建新会话项
			async createSessionByMsg(msg, sessionId) {
				let sessionTemp = {
					channelId: uni.IM.createChannelIdBySessionId(sessionId),
					sessionId,
					lastMsg: msg.data,
					chatType: msg.type,
					time: msg.time,
					unreadNum: msg.from == uni.IM.userId ? 0 : 1,
					messageType: msg.ext.messageType,
					error: msg.error,
					userName: msg.ext.userName,
					senderId: msg.from,
					atList: [],
				}
				const {
					session
				} = await this.findSessionBySessionId(this.groupSessionList, sessionTemp.sessionId);
				console.log('从群组列表中找到的session>>>>>>>>>>>>', session);
				if (session && sessionTemp.chatType == 'groupChat') {
					sessionTemp.sessionName = session.sessionName;
					sessionTemp.sessionAvatar = session.sessionAvatar;
					sessionTemp.atList = session.atList;
				} else {
					const {
						sessionName,
						sessionAvatar
					} = await this.getSessionExtensionInfo(sessionTemp.sessionId.split('^')[0], sessionTemp.chatType);
					sessionTemp.sessionName = sessionName;
					sessionTemp.sessionAvatar = sessionAvatar;
				}
				console.log('sessionTemp>>>>>>>>>>>>>>>>>', sessionTemp)
				return sessionTemp;
			},
			searchWordKey(e) {
				this.wordKey = e;
			},
			//设置tabbar未读消息数
			setUnreadNum() {
				let unreadNum = 0;
				this.recentlySessionList.forEach(item => {
					unreadNum += item.unreadNum;
				})
				this.$u.vuex('globalUnreadNum', unreadNum);
			},
			scroll() {

			},
			//双击tabbar回调函数
			onDoubleTap() {
				if (!this.unreadSessionList.length) {
					return
				} else if (!this.scrollCurrentId) {
					this.scrollCurrentId = this.unreadSessionList[0];
				} else {
					this.scrollCurrentId = this.unreadSessionList[this.unreadSessionList.indexOf(this.scrollCurrentId) +
						1] ? this.unreadSessionList[this.unreadSessionList.indexOf(this.scrollCurrentId) +
						1] : this.unreadSessionList[0];
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "./sessionList.scss";
</style>
